<template>
  <div class="bug-treemap-container">
    <div class="bug-treemap-container__title">{{ props.title }}</div>
    <div ref="chartsRef" class="bug-treemap-container__chart"></div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, Ref, onMounted, onUnmounted } from 'vue';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { TreemapChart } from 'echarts/charts';
  const props = defineProps({
    title: {
      type: String,
      default: '',
    },
    // 正式的数据传到这个参数中
    data: {
      type: Array as PropType<{ name: string; path: string; value: number }[]>,
      default: () => [],
    },
    unit: {
      type: String,
      default: '个',
    },
  });
  const chartsRef = ref<HTMLDivElement>();
  const { setOptions, echarts } = useECharts(chartsRef as Ref<HTMLDivElement>);
  echarts.use([TreemapChart]);
  var timer: TimeoutHandle | null = null;
  const deshark = (callback: () => void) => {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      callback();
    }, 50);
  };

  const myObserver = new ResizeObserver(() => {
    // 宽度发生了变化
    deshark(methods.reload);
  });

  const methods = {
    reload() {
      // 先设置高度
      if (chartsRef.value) {
        chartsRef.value.style.height = chartsRef.value.clientWidth + 'px';
      }
      setOptions({
        tooltip: {
          show: true,
        },
        series: [
          {
            name: props.title,
            type: 'treemap',
            label: {
              show: true,
              formatter: '{b}',
            },
            itemStyle: {
              borderColor: '#fff',
            },
            data: props.data,
          },
        ],
      });
    },
  };

  onMounted(() => {
    methods.reload();
    if (chartsRef.value) {
      myObserver.observe(chartsRef.value);
    }
  });
  onUnmounted(() => {
    // 清空下防止内存溢出
    if (chartsRef.value) {
      myObserver.unobserve(chartsRef.value);
      myObserver.disconnect();
    }
  });
</script>

<style lang="less" scoped>
  .bug-treemap-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .bug-treemap-container__title {
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
    }
  }
</style>
